package com.cfjjc.gz.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import com.cfjjc.gz.common.exception.OTSException;

/**
 * java对象操作实用类
 * 
 * @author lx
 * 
 */
public class BeanUtil {

	/**
	 * logger对象
	 */
	private static final Logger logger = Logger.getLogger(BeanUtil.class);
	/**
	 * 克隆一个给定的bean对象。
	 * <p>
	 * 注意：该方法只是提供浅层克隆，也就是说对象里存在对象时子对像不会被克隆。
	 * 
	 * @param bean
	 * @return
	 * @throws OTSException
	 */
	public static Object cloneBean(Object bean) throws OTSException {
		try {
			Object clonedBean = BeanUtils.cloneBean(bean);
			return clonedBean;
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new OTSException("数据转换出现异常，请刷新页面后重试或联系管理员！");
		}
	}

	/**
	 * 深度克隆一个给定的bean对象。
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	public static Object deepCloneBean(Object bean) throws Exception {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream outStream = new ObjectOutputStream(byteOut);
		outStream.writeObject(bean);
		ByteArrayInputStream byteIn = new ByteArrayInputStream(
				byteOut.toByteArray());
		ObjectInputStream inStream = new ObjectInputStream(byteIn);
		return inStream.readObject();
	}
	
	public static void setProperty(Object bean, String name, Object value) throws OTSException {
		try {
			BeanUtils.setProperty(bean, name, value); 
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new OTSException("数据赋值出现异常，请刷新页面后重试或联系管理员！");
		}
	}
	
	/**
	 * 将map对象转化为pojo对象
	 * @param bean
	 * @param properties
	 * @throws OTSException
	 */
	public static void populate(Object bean, Map properties) throws OTSException {
		try {
			BeanUtils.populate(bean, properties);
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new OTSException("数据赋值出现异常，请刷新页面后重试或联系管理员！");
		}
	}
}
